What is Borrowing, Reference (&)
-
In reference & Borrowing ownership of the value is not taken.
References are always created using &
Rust track lifetimes of all references to ensure they live long enough
Wrt to C++:
Safer avoids Crashes/Dangling References.
no new copies are created, achieved by passing the reference of a variable.
Reference vs Borrowing
Reference (immutable) | Borrowing (Mutable Reference) | |
---|---|---|
Definition |
A reference is just a pointer storing address of variable. References are immutable.
|
Borrowed value can be changed.
|
Types of Borrowing
Dangling References (Allowed in C++, but not in Rust)
Dangling reference? Similar to Dangling pointer, when reference to a value is used, value is freed and reference is used after that.
C++ (Crash in C++) | Rust | |
---|---|---|
Dangling References |
Dangling References Allowed in C++
|
Dangling References Not Allowed in Rust
|
Exclusive/Mutable References (&mut T)
- (By default)References are IMMUTABLE in Rust, we need to make them mutable explicitly.
C++ | Rust | |||
---|---|---|---|---|
Mutable? |
References are mutable by Default in C++
|
References are IMMUTABLE by Default in Rust
|
Two Mutable references not allowed in same scope
-
Why Rust avoids 2 mutable ref in same scope?
To prevent data race b/w 2 threads. 1 mutable ref change and other also change.
C++ Crash
|
Rust(No Crash, But compiletime error) Why not allowed in Rust? This can be a race condition, where if both mutable references change the data, there is no mechanism synchronize access to the data
|
1 Immutable, 1 Mutable reference not allowed in same scope
This happens because immutable reference is used after mutable
|